<template>
  <div class="search">
    <Card>
      <div class="totalCount">
        <p class="countTitle">合计</p>
        <div class="totalList">
          <p>
            充值钱包余额：<span>{{ allData.rechargeMoney }}</span>
          </p>
          <p>
            充值现金总额：<span>{{ allData.allRechargeMoney }}</span>
          </p>
          <p>
            推广会员费钱包余额：<span>{{ allData.promoteHyMoney }}</span>
          </p>
          <p>
            推广服务费钱包余额：<span>{{ allData.promoteFwMoney }}</span>
          </p>
          <p>
            焕贝总额：<span>{{ allData.allMoney }}</span>
          </p>
        </div>
      </div>
      <Row @keydown.enter.native="handleSearch">
        <Form ref="searchForm" :model="searchForm" inline :label-width="70" class="search-form">
          <Form-item label="注册时间">
            <DatePicker v-model="selectDate" type="datetimerange" format="yyyy-MM-dd" clearable @on-change="selectDateRange" placeholder="选择起始时间" style="width: 300px"></DatePicker>
          </Form-item>
          <Form-item label="联系方式" prop="mobile">
            <Input type="text" v-model="searchForm.mobile" placeholder="请输入会员联系方式" clearable style="width: 200px" />
          </Form-item>
          <Form-item label="区域" prop="name" v-show="userEnums == 'MANAGER'">
            <regionArea ref="region" style="width: 350px" @selected="selectedRegions" :showIs="true" />
          </Form-item>
          <Button @click="handleSearch" class="search-btn" type="primary" icon="ios-search">搜索</Button>

          <Button class="search-btn" type="primary" @click="handleReset">重置</Button>
          <download-excel class="export-excel-wrapper" :data="data" :fields="fields" :fetch="exportOrder" name="城市合伙人.xls">
            <Button type="info" class="export"> 导出 </Button>
          </download-excel>
        </Form>
      </Row>

      <Table :loading="loading" border :columns="columns" class="mt_10" :data="data" ref="table"></Table>
      <Row type="flex" justify="end" class="mt_10">
        <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize" @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10, 20, 50, 100]" size="small" show-total show-elevator show-sizer></Page>
      </Row>
    </Card>
    <Modal width="1500px" v-model="bindModal" title="绑定会员" @on-visible-change="modalChange">
      <bindMemberModal ref="bindMember"></bindMemberModal>
      <template #footer>
        <Button size="large" @click="bindModal = false">取消</Button>
        <Button type="primary" size="large" :loading="modal_loading" @click="bindMemberData">立即绑定</Button>
      </template>
    </Modal>
    <Modal title="推广码" v-model="qrcodeModalVisible" :mask-closable="false" :width="500">
      <div style="text-align: center;">
        <img :src="image" style="height: 220px;margin-top: 1px;width: 220px">
      </div>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>
import region from "@/views/lili-components/region"
import * as API_Member from "@/api/member.js"
import * as API_Partner from "@/api/partner.js"
import * as API_Agent from "@/api/agent.js"
import ossManage from "@/views/sys/oss-manage/ossManage"
import regionArea from "@/views/agent-manage/region"
import JsonExcel from "vue-json-excel"
import bindMemberModal from "@/views/partner-manager/components/bindMember"
import { getStore, setStore } from "@/libs/storage.js"
import { SunCode } from "@/api/goods.js"

export default {
  name: "city-partner",
  components: {
    region,
    regionArea,
    ossManage,
    "download-excel": JsonExcel,
    bindMemberModal,
  },
  data () {
    return {
      image: '',
      qrcodeModalVisible: false, //收款码显示弹窗
      userEnums: "",
      // 表格的表头以及内容
      fields: {
        姓名: "realName",
        身份证号: {
          field: "idCardNumber",
          callback: (value) => {
            return "&nbsp;" + value
          },
        },
        会员昵称: "nickName",
        手机号码: {
          field: "mobile",
          callback: (value) => {
            return "&nbsp;" + value
          },
        },
        级别: "gradeName",
        区域: {
          field: "locationName",
          callback: (value) => {
            return "&nbsp;" + value
          },
        },
        推荐人姓名: "recommendName",
        推荐人手机号: {
          field: "recommendPhone",
          callback: (value) => {
            return "&nbsp;" + value
          },
        },
        推广会员数: "quantity",
        注册时间: "beginTime",
        到期时间: "endTime",
        充值钱包余额: "rechargeMoney",
        充值现金总额: "allRechargeMoney",
        推广会员费钱包余额: "promoteHyMoney",
        推广服务费钱包余额: "promoteFwMoney",
        焕贝总额: "allMoney",
      },
      modal_loading: false,
      loading: true, // 表单加载状态
      updateRegion: false, // 地区
      selectDate: null, // 选择时间段
      searchForm: {
        // 请求参数
        pageNumber: 1,
        pageSize: 10,
        order: "desc",
        mobile: "", //联系方式
        roleType: "AGENT", //用户类型
        regionId: "", //区域
        beginTime: "", //下单时间
        endTime: "",
        recommendPhone:'',
        recommendName:'',
      },
      columns: [
        {
          title: "序号",
          type: "index",
          width: 80,
          align: "center",
        },
        {
          title: "姓名",
          key: "realName",
          width: "150",
          tooltip: true,
        },
        {
          title: "身份证号",
          key: "idCardNumber",
          width: "150",
          tooltip: true,
        },
        {
          title: "会员昵称",
          key: "nickName",
          width: "150",
          tooltip: true,
        },
        {
          title: "手机号码",
          key: "mobile",
          width: "150",
        },
        {
          title: "级别",
          key: "gradeName",
          width: "150",
        },

        {
          title: "区域",
          key: "locationName",
          width: "300",
          tooltip: true,
        },
          {
          title: "推荐人姓名",
          key: "recommendName",
          width: "160",
          tooltip: true,
        },
        {
          title: "推荐人手机号",
          key: "recommendPhone",
          width: "140",
          tooltip: true,
        },
        {
          title: "推广会员数",
          key: "quantity",
          width: "300",
          tooltip: true,
        },
        {
          title: "注册时间",
          key: "beginTime",
          width: "250",
        },
        {
          title: "到期时间",
          key: "endTime",
          width: "250",
        },
        {
          title: "充值钱包余额",
          key: "rechargeMoney",
          width: "150",
        },
        {
          title: "充值现金总额",
          key: "allRechargeMoney",
          width: "150",
        },
        {
          title: "推广会员费钱包余额",
          key: "promoteHyMoney",
          width: "150",
        },
        {
          title: "推广服务费钱包余额",
          key: "promoteFwMoney",
          width: "150",
        },
        {
          title: "焕贝总额",
          key: "allMoney",
          width: "150",
        },
        {
          title: "操作",
          key: "action",
          align: "center",
          minWidth: 300,
          fixed: "right",
          render: (h, params) => {
            return h(
              "div",
              {
                style: {
                  display: "flex",
                  justifyContent: "center",
                },
              },
              [
                h(
                  "Button",
                  {
                    props: {
                      type: "info",
                      size: "small",
                    },
                    style: {
                      marginRight: "5px",
                      display: this.selectedMember ? "none" : "block",
                    },
                    on: {
                      click: () => {
                        this.detail(params.row)
                      },
                    },
                  },
                  "详情"
                ),
                h(
                  "Button",
                  {
                    props: {
                      size: "small",
                      type: "primary",
                    },
                    style: {
                      marginRight: "5px",
                    },
                    on: {
                      click: () => {
                        this.bindMember(params.row, params.index)
                      },
                    },
                  },
                  "绑定会员"
                ),
                h(
                  "Button",
                  {
                    props: {
                      size: "small",
                      type: "error",
                    },
                    style: {
                      marginRight: "5px",
                      display: this.selectedMember ? "none" : "block",
                    },
                    on: {
                      click: () => {
                        this.disabled(params.row)
                      },
                    },
                  },
                  "禁用"
                ),
								h(
								  "Button",
								  {
								    props: {
								      size: "small",
								      type: "error",
								    },
								    style: {
								      marginRight: "5px",
								    },
								    on: {
								      click: () => {
								        this.zhuxiao(params.row)
								      },
								    },
								  },
								  "注销"
								),
                h(
                  "Button",
                  {
                    props: {
                      type: "success",
                      size: "small",
                    },
                    style: {
                      display:
                        params.row.auditState == "APPLYING" ? "" : "none",
                    },
                    on: {
                      click: () => {
                        this.apply(params.row)
                      },
                    },
                  },
                  "审核"
                ),
                h(
                  "Button", {
                  props: {
                    type: "info",
                    size: "small",
                    ghost: true,
                  },
                  style: {
                    marginRight: "5px",
                  },
                  on: {
                    click: () => {
                      this.qrcode(params.row)
                    },
                  },
                },
                  "推广码"
                ),
              ]
            )
          },
        },
      ],
      data: [], // 表单数据
      total: 0, // 表单数据总数
      selectMember: [], //保存选中的用户
      allData: {}, //获取列表总总额的数据
      bindModal: false, //绑定会员弹框
      memberJson: {}, //点击绑定会员，获取到对应的数据json值
    }
  },
  props: {
    // 是否为选中模式
    selectedMember: {
      type: Boolean,
      default: false,
    },
    // 已选择用户数据
    selectedList: {
      type: null,
      default: () => {
        return []
      },
    },
  },
  watch: {
    selectedList: {
      handler (val) {
        this.$set(this, "selectMember", JSON.parse(JSON.stringify(val)))
        this.init(this.data)
        // 将父级数据与当前组件数据进行匹配
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    //收款码按钮
    async qrcode (row) {
      this.image = ''
      await SunCode({
        scene: `/pages/tabbar/home/page/InterceptPage?scene=${row.promotionCode}`,
        page: 'pages/product/customerservice/index'
      }).then(res => {
        this.image = 'data:image/png;base64,' + res.result.sunCode
      })
      this.qrcodeModalVisible = true
    },
    // 导出订单
    async exportOrder () {
      if (this.searchForm.regionId) {
        this.searchForm.regionId = this.searchForm.regionId.toString()
      }

      this.searchForm.auditStates = "PASS"
      const params = JSON.parse(JSON.stringify(this.searchForm))
      params.pageNumber = 1
      params.pageSize = 999999999
      const result = await API_Partner.getMemberListData(params)
      if (result.success) {
        if (result.result.records.length === 0) {
          this.$Message.warning("暂无可导出数据")
          return []
        } else {
          return result.result.records
        }
      } else {
        this.$Message.warning("导出数据失败，请重试")
      }
    },
    // 重置
    handleReset () {
      this.selectDate = ""
      this.searchForm = {
        // 请求参数
        pageNumber: 1,
        pageSize: 10,
        order: "desc",
        mobile: "", //联系方式
        roleType: "AGENT", //用户类型
        regionId: "", //区域
        beginTime: "", //下单时间
        endTime: "",
      }
      this.$refs.region.addr = []
      this.getData()
    },
    // 获取绑定会员组件选中的会员数据
    bindMemberData () {
      //获取选中的数据数组
      let params = {
        partnerId: this.memberJson.partnerId,
        promotionCode: this.memberJson.promotionCode,
        choseBindMemberIds: this.$refs.bindMember.choseIds,
      }
      if (params.choseBindMemberIds && params.choseBindMemberIds.length > 0) {
        this.bindModal = false
        API_Partner.bindingNoPartnerMemberList(params).then((res) => {
          if (res.code == 200) {
            this.$Message.success("绑定会员成功")
            this.$refs.bindMember.getData()
            this.getData()
          }
        })
      } else {
        this.bindModal = true
        this.$Message.info("请选择要绑定的会员")
      }
    },
    modalChange (v) {
      if (v == false) {
        this.$refs.bindMember.choseDataList = []
        this.$refs.bindMember.choseIds = []
        this.$refs.bindMember.$refs.table.selectAll(false)
      }
    },
    // 绑定会员
    bindMember (val) {
      this.bindModal = true
      this.memberJson = val
    },
    // 选择日期
    selectDateRange (v) {
      if (v) {
        this.searchForm.beginTime = v[0]
        this.searchForm.endTime = v[1]
      }
    },
    // 选中的地址
    selectedRegions (val) {
      this.searchForm.regionId = val[0]
    },

    // 回调给父级
    callback (val, index) {
      this.$set(val, "___selected", !val.___selected)
      let findUser = this.selectMember.find((item) => {
        return item.id == val.id
      })
      // 如果没有则添加
      if (!findUser) {
        this.selectMember.push(val)
      } else {
        // 有重复数据就删除
        this.selectMember.map((item, index) => {
          if (item.id == findUser.id) {
            this.selectMember.splice(index, 1)
          }
        })
      }

      this.$emit("callback", val)
    },
    // 初始化信息
    init (data) {
      data.forEach((item) => {
        if (this.selectMember.length != 0) {
          this.selectMember.forEach((member) => {
            if (member.id == item.id) {
              this.$set(item, "___selected", true)
            }
          })
        } else {
          this.$set(item, "___selected", false)
        }
      })
      this.data = data
    },
    // 分页 改变页码
    changePage (v) {
      this.searchForm.pageNumber = v
      this.getData()
    },
    // 分页 改变页数
    changePageSize (v) {
      this.searchForm.pageSize = v
      this.searchForm.pageNumber = 1
      this.getData()
    },
    // 搜索
    handleSearch () {
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = 10
      this.getData()
    },
    //查询会员列表
    getData () {
      this.loading = true
      if (this.searchForm.regionId) {
        this.searchForm.regionId = this.searchForm.regionId.toString()
      }
      this.searchForm.auditStates = "PASS"
      API_Partner.getMemberListData(this.searchForm).then((res) => {
        if (res.result.records) {
          this.loading = false
          this.init(res.result.records)
          this.total = res.result.total
        }
      })
      API_Partner.partnerListAll(this.searchForm).then((res) => {
        if (res.code == 200) {
          this.allData = res.result
        }
      })
    },
    //查看会员
    detail (row) {
      this.$router.push({
        // path:'/user-partner-detailB',
        name: "city-partner-detail",
        query: {
          id: row.id,
          regionId: row.partnerRegionId,
        },
      })
    },
    //禁用会员
    disabled (v) {
      let params = {
        id: [v.id],
        partnerState: 1,
      }
      this.$Modal.confirm({
        title: "提示",
        content: "<p>确认禁用该会员账号吗？禁用后请在“异常会员列表”查找？</p>",
        onOk: () => {
          API_Member.updatePartner(params).then((res) => {
            if (res.success) {
              this.$Message.success("禁用成功")
              this.getData()
            } else {
              // this.$Message.error(res.message);
            }
          })
        },
      })
    },
	// 注销合伙人
		zhuxiao (v) {
			let that = this
			this.$Modal.confirm({
			  title: "注销合伙人",
			  content: "确认注销此合伙人吗?",
			  render: (h) => {
			    let html = [
			      h("div", {}, "确认注销此合伙人吗？"),
			    ]
			    html.push(
			      h(
			        "div",
			        {
			          class: {
			            modalClass: true,
			          },
			        },
			        [
			          h("span", "备注"),
			          h("Input", {
			            props: {
			              name: "123",
			              value: that.revokeMsg,
			              autofocus: true,
			              width: "20px",
			              placeholder: "请输入备注",
			            },
			            on: {
			              input: (val) => {
			                that.revokeMsg = val
			              },
			            },
			          }),
			        ]
			      )
			    )
			    return html
			  },
			  onOk: () => {
					if(!that.revokeMsg){
						this.$Message.error("请输入备注")
						return
					}
					let params = {
					  memberId: v.id,
					  revokeMsg: that.revokeMsg,
					}
			    API_Member.disablePartner(params).then((res) => {
			      if (res.code == 200) {
			        this.$Message.success("合伙人注销成功")
			        this.getData()
					that.revokeMsg = ""
			      }
			    })
			  },
			  onCancel: () => {
			    that.revokeMsg = ""
			  },
			})
		}
  },
  mounted () {
    this.getData()
    this.userEnums = this.getStore("userEnums")
  },
};
</script>
<style lang="scss">
.modalClass {
  display: flex;
  align-items: center;
  span {
    flex-shrink: 0;
    margin-right: 10px;
  }
}
</style>
<style lang="scss" scoped>
.export-excel-wrapper {
  margin-left: 10px;
}
/deep/ .ivu-table-wrapper {
  width: 100%;
}

/deep/ .ivu-card {
  width: 100%;
}

.face {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}

.totalCount {
  width: 100%;
  height: auto;
  .countTitle {
    width: 100%;
    height: auto;
    font-weight: bold;
    font-size: 24px;
  }
  .totalList {
    display: flex;
    align-items: center;
    p {
      margin-right: 20px;
      font-size: 18px;
      span {
        margin-left: 10px;
      }
    }
  }
}
</style>
